import { useEffect, useRef } from 'react'
import THREEProject from '../utils/index'

const BufferGeometry = () => {
  const can = useRef(null)
  const pro = new THREEProject()
  const { thr, renderer, scene, axes, camera, controls } = pro
  const fileLoader = new thr.FileLoader()
  const init = () => {
    scene.add(axes)

    const geometry = new thr.BufferGeometry()
    const vertices = new Float32Array([
      0.0, 0.0, 0.0,
      0.0, 3.0, 0.0,
      3.0, 0.0, 0.0,
      0.0, 0.0, 3.0,
      3.0, 3.0, 0.0,
      0.0, 3.0, 3.0,
      3.0, 0.0, 3.0,
      3.0, 3.0, 3.0
    ])
    const material = new thr.MeshBasicMaterial({
      color: 0xffccff,
      side: thr.DoubleSide,
    })
    fileLoader.load('/assets/xyztest2.json', res => {
      console.log(res)
      const vertices = new Float32Array(JSON.parse(res).data)
      console.log("🚀 ~ file: BufferGeometry.js ~ line 30 ~ init ~ vertices", vertices)
      geometry.setAttribute('position', new thr.BufferAttribute(vertices, 3))
      const mesh = new thr.Mesh(geometry, material)

      scene.add(mesh)
    })

    scene.add(new thr.AmbientLight(0xffffff))
    appendRenderDom()
    animate()
  }

  const appendRenderDom = () => {
    if(!can.current.children.length) {
      can.current.appendChild(renderer.domElement)
    }
  }

  const render = () => {
    controls.update()
    renderer.render(scene, camera)
  }

  const animate = () => {
    requestAnimationFrame(animate)
    render()
  }

  useEffect(init, [])

  return (
    <div ref={can}></div>
  )
}

export default BufferGeometry
export {
  BufferGeometry
}